<template>
  <div class="meeting-place-wrap">
    <van-pull-refresh v-model="isRefresh" @refresh="onDownRefresh">
      <header id="header">
        <!-- banner -->
        <div v-if="bannerList.length > 0">
          <banner-list :bannerList="bannerList" />
        </div>
        <!-- 金刚位 -->
        <diamond-list
          v-if="diamondList.length > 0"
          :diamondList="diamondList"
        />
        <!-- 生活频道 -->
        <lifeChannel :lifeTabList="lifeTabList" v-if="lifeTabList.length > 0" />
        <div @click="lifeTabList = []">清空list数据，相应的列表会重新渲染</div>
      </header>
      <!-- 频道 -->
      <!-- 吸顶的那一刻伴随抖动 给吸顶元素加一个父级元素 -->
      <div id="fixed-tab-root">
        <div id="tab-wrap" :class="tabFixed ? 'isFixed' : ''">
          <div class="channel-list" :class="{ w100: channelList.length <= 4 }">
            <van-tabs
              class="van-tabs_custom_activity"
              @click="handleChangeTab"
              v-model="activeIndex"
            >
              <van-tab
                v-for="tab in channelList"
                :title="tab.name"
                :key="tab.id"
                class="van-tab_custom"
              >
              </van-tab>
            </van-tabs>
          </div>
          <!-- 下拉按钮 -->
          <div
            class="drop-down"
            @click="toggleChannel"
            v-if="channelList.length > 4"
          >
            <img src="@/assets/images/activity/icon-down-select.png" alt="" />
          </div>
        </div>
      </div>
      <!-- 主内容区域 -->
      <van-list
        v-model="isLoading"
        :finished="isFinished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="onLoadMore"
        :style="{ minHeight: '100vh' }"
      >
        <!-- 商品列表 -->
        <div
          class="list-wrapper"
          :class="{
            between: colType === 2,
            'col-3': colType === 3,
            pt48: tabFixed
          }"
        >
          <div v-for="(product, index) in list" :key="index">
            <insertCard
              v-if="product.type"
              :type="product.type"
              :productList="list"
              :productType="colType"
            />
            <template v-else>
              <one-col-product v-if="colType === 1" :product="product" />
              <two-col-product v-else-if="colType === 2" :product="product" />
              <three-col-product v-else-if="colType === 3" :product="product" />
            </template>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
    <!-- channel下拉选择弹窗 -->
    <channel-popup
      ref="channelPopupRef"
      :channelList="channelList"
      :curTabIndex="curTabIndex"
      @selectTab="selectTab"
    />
  </div>
</template>

<script>
import diamondList from './components/diamondList.vue';
import bannerList from './components/bannerList.vue';
import oneColProduct from './components/oneColProduct.vue';
import twoColProduct from './components/twoColProduct.vue';
import threeColProduct from './components/threeColProduct.vue';
import insertCard from './components/insertCard.vue';
import channelPopup from './components/channelPopup.vue';
import lifeChannel from './components/lifeChannel.vue';

export default {
  name: 'meetingPlace',
  components: {
    bannerList,
    diamondList,
    channelPopup,
    oneColProduct,
    twoColProduct,
    threeColProduct,
    insertCard,
    lifeChannel
  },
  data() {
    return {
      bannerList: [
        {
          id: 1,
          imgUrl:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1568992955029037.jpg'
        }
      ],
      diamondList: [
        {
          id: '1',
          name: '金刚位1',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1568992955029037.jpg',
          href: 'invitorList'
        },
        {
          id: '2',
          name: '金刚位2',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1568993005301607.jpg',
          href: 'group-buy/group-list'
        },
        {
          id: '2',
          name: '金刚位3',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1568993005301607.jpg',
          href: 'group-buy/group-list'
        },
        {
          id: '5',
          name: '金刚位4',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1568993409185651.jpg',
          href: 'landingPage?conferenceId=162&type=2'
        },
        {
          id: '6',
          name: '金刚位5',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'allBuying'
        },
        {
          id: '7',
          name: '金刚位6',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'superMarket'
        },
        {
          id: '8',
          name: '金刚位7',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'top-list'
        },
        {
          id: '9',
          name: '金刚位8',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'commonActivity?conferenceId=254'
        },
        {
          id: '10',
          name: '金刚位9',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'bannerLanding'
        },
        {
          id: '11',
          name: '金刚位10',
          img:
            'https://akminiapp-qrcode.oss-cn-shanghai.aliyuncs.com/miniappcode/1569002512153782.jpg',
          href: 'commonActivity?conferenceId=255'
        }
      ],
      lifeTabList: [
        { id: 1, name: '你好轻松' },
        { id: 2, name: '你好伤心' },
        { id: 3, name: '你好开心' },
        { id: 4, name: '你好苦逼' }
      ], // { id: 5, name: '你好苦逼' },{ id: 6, name: '你好苦逼' }
      lifeProdList: [1, 2, 3, 4, 5, 6, 7, 8],

      channelList: [
        { id: 13, name: '母婴' },
        { id: 39, name: '预告3' },
        { id: 11, name: '男装' },
        { id: 38, name: '预告002' },
        { id: 37, name: '预告001' }
        // { id: 12, name: '女装' },
        // { id: 18, name: '14' },
        // { id: 17, name: '13' },
        // { id: 6, name: 'test2' },
        // { id: 14, name: '10' },
        // { id: 15, name: '11' },
        // { id: 5, name: '超市频道' },
        // { id: 9, name: 'xing2' }
      ],

      cache: {}, // 缓存
      tabFixed: false, // tab
      channelId: null, // 选中的channelId
      channelName: null, // 选中的channelName
      curTabIndex: 0, // 当前选中的channel下标
      activeIndex: 0,

      colType: 3, // 1: 1列商品, 2: 2列商品, 3: 3列商品
      list: [],
      isRefresh: false, // 下拉刷新
      isLoading: false, // 上拉加载
      isFinished: false, // 上拉加载完毕
      pageNum: 1, // 页码
      pageSize: 12, // 一页加载多少条,
      isScroll: false,
      totalHeight: 0
      // isChange: false,
    };
  },
  methods: {
    addToCache(proList) {
      this.cache[this.channelId] = {
        finished: this.isFinished,
        pageNum: this.pageNum,
        list: proList,
        colType: this.colType
      };
    },
    selectTab(index) {
      if (index === this.curTabIndex) return;
      this.curTabIndex = index;
      this.activeIndex = index;
      this.channelId = this.channelList[index].id;
      this.channelName = this.channelList[index].name;
      // 查看是否有缓存
      if (this.cache[this.channelId]) {
        const cacheData = this.cache[this.channelId];
        const { list, pageNum, isFinished, colType } = cacheData;
        this.colType = colType;
        this.list = list;
        this.pageNum = pageNum;
        this.isFinished = isFinished;
      } else {
        this.resetTabData();
      }
    },
    handleChangeTab(index, title) {
      console.log(index, title);
      if (index === this.curTabIndex) return;
      this.curTabIndex = index;
      this.channelId = this.channelList[index].id;
      if (this.tabFixed) {
        this.scrollToTab();
      }
      // 查看是否有缓存
      if (this.cache[this.channelId]) {
        const cacheData = this.cache[this.channelId];
        const { list, pageNum, isFinished, colType } = cacheData;
        this.colType = colType;
        this.list = list;
        this.pageNum = pageNum;
        this.isFinished = isFinished;
      } else {
        this.resetTabData();
      }
    },
    scrollToTab() {
      const headerDOM = document.getElementById('header');
      const headerHeight = headerDOM ? headerDOM.offsetHeight + 10 : 0;
      const tabNavDom = document.querySelector('.fixed-tab-nav');
      const tabNavHeight = tabNavDom ? tabNavDom.offsetHeight : 0;
      this.totalHeight = headerHeight + tabNavHeight;
      console.log('==totalHeight==', headerHeight, tabNavHeight);
      console.log('==totalHeight==', this.totalHeight);
      window.scrollTo(0, this.totalHeight);
    },
    toggleChannel() {
      const Dom = document.getElementById('tab-wrap');
      if (this.tabFixed) {
        if (this.$refs.channelPopupRef) {
          this.$refs.channelPopupRef.showPopup();
        }
        return;
      }
      const DomT = Dom ? Dom.offsetTop : 0;
      window.scrollTo(0, DomT);
      this.tabFixed = true;
      if (this.$refs.channelPopupRef) {
        this.$refs.channelPopupRef.showPopup();
      }
    },
    // 下拉刷新
    onDownRefresh() {
      this.pageNum = 1;
      this.isFinished = false;
      this.list = [];
      this.getData(); // 加载数据
    },
    // 上拉加载
    onLoadMore() {
      if (this.pageNum === 1) {
        this.isLoading = false;
        return;
      }
      this.getData();
    },
    resetTabData() {
      this.pageNum = 1;
      this.isFinished = false; // 上拉到底过后,再下拉刷新, 触发下拉加载事件
      this.isLoading = false;
      this.list = [];
      this.getData();
    },
    createList(start) {
      const data = [];
      for (let i = start; i < 18; i += 1) {
        data.push({
          id: `id${start + 1}`
        });
      }
      return data;
    },
    getData() {
      console.log('getData====', this.channelId);
      this.colType =
        (this.curTabIndex + 1) % 3 > 0 ? (this.curTabIndex + 1) % 3 : 3;
      this.channelId = this.channelList[this.curTabIndex].id;

      if (this.pageNum === 1) {
        this.list = this.createList(0);
      } else {
        const newList = this.createList(this.pageNum - 1);
        this.list = this.list.concat(newList);
      }
      this.addToCache(this.list); // 把数据加入缓存
      this.pageNum += 1;
      // const insertCardList = [
      //   { id: 1, type: 2, position: 1 },
      //   { id: 7, type: 1, position: 7 },
      //   { id: 11, type: 2, position: 11 },
      //   { id: 15, type: 1, position: 15 }
      // ];
      //
      // insertCardList.forEach(item => {
      //   this.productList.splice(item.position * this.colType, 0, item);
      // });
      this.isRefresh = false;
      this.isLoading = false;
    },
    handleScroll() {
      this.isScroll = true;
      if (this.channelList.length > 1) {
        const headerDOM = document.getElementById('header');
        if (headerDOM) {
          let bottom = headerDOM.getBoundingClientRect().bottom + 10;
          this.tabFixed = bottom <= 0;
        } else {
          this.tabFixed = true;
        }
      }
    },
    // throttle和IntersectionObserver 方案结合起来使用
    scrollFunc() {
      const headerDOM = document.getElementById('header');
      if (IntersectionObserver) {
        const observer = new IntersectionObserver(this.handleScroll, {
          // 100%时触发回调函数
          threshold: [1]
        });
        observer.observe(headerDOM);
      } else {
        // window.addEventListener('scroll', throttle(this.handleScroll, 20));
      }
    }
  },
  mounted() {
    this.getData();
    window.addEventListener('scroll', this.handleScroll, false);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll, false);
  }
};
</script>

<style lang="scss" scoped>
.meeting-place-wrap {
  background-color: #f5f5f5;
  position: relative;
  min-height: 100vh;

  #header {
    padding: 0 0.2rem;
    margin-bottom: 0.24rem;
  }

  .isFixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 2000;
    transition: top 0.3s ease;
  }
  #tab-wrap {
    width: 100%;
    display: flex;

    .channel-list {
      width: 6.58rem;
    }

    .w100 {
      width: 100%;
    }

    .drop-down {
      width: 0.92rem;
      height: 0.76rem;
      background: #fff;
      img {
        width: 0.92rem;
        height: 0.76rem;
        vertical-align: top;
        display: block;
      }
    }
  }

  .list-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding: 0.2rem 0.24rem 0;
  }

  .between {
    justify-content: space-between;
  }

  .col-3 {
    padding: 0.2rem 0.18rem 0;
  }

  .pt48 {
    padding-top: 48px;
  }

  .van-tab_custom {
    /*padding-top: 0.2rem;*/
  }
}
</style>

<style lang="scss">
.van-tabs_custom_activity {
  .van-tabs__wrap {
    z-index: 1002;
    height: 38px !important;
  }

  .van-tab {
    line-height: 38px !important;
    flex-basis: 23% !important;
  }
  .van-tabs__line {
    width: 56px !important;
    height: 2px !important;
    background-color: #e62525 !important;
  }
  .van-tab--active {
    font-weight: 400 !important;
    color: #e62525 !important;
  }
}
</style>
